package android.vstore.activities;

import gin.dev.update.DownloadNotification;
import gin.dev.update.DownloadQuere;
import gin.dev.update.DownloadTask;
import gin.dev.update.IOnDownload;
import gin.dev.update.Installation;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import DTO.ImageDTO;
import DTO.ProductDTO;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.vstore.fragment.PageHorizalGalleryFragment;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import anroid.vstore.provider.Constant;
import anroid.vstore.provider.Helper;
import anroid.vstore.provider.SharedPreference;

import com.appvn2014.appstorevn.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class SceneDetailItemActivity extends BaseActivity implements OnClickListener{

	protected static final int NOTIFICATION_COMING = 0;
	public static int NON = 0;
	public static int ALREADY_INSTALLED = 1;
	public static String URL_HEADER = Helper.SERVICE_URL;

	Button mBtnInstall,mBtnUninstall;
	ProgressBar mPbProgress;

	ProductDTO item = null;

	BroadcastReceiver myReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// do whatever you want to do
			Log.i("TAG", "Installed!!");
			if(intent.hasExtra("productID") == true)
			{
				int id = intent.getIntExtra("productID", -1);
				if(id != -1)
				{
					mBtnInstall.setText(R.string.detail_activity_open_app_name);
					mBtnUninstall.setText(R.string.detail_activity_remove_app);
					mBtnInstall.setVisibility(View.VISIBLE);
					mBtnUninstall.setVisibility(View.VISIBLE);
				}
			}
		}
	};
	private View count;
	private TextView notifCount;
	private FrameLayout notiLay;
	private boolean isCheckedNotification;
	private MenuItem notification;
	private Integer listNotf;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scene_detail_item);

		mBtnInstall = (Button) findViewById(R.id.btn_detail_action);
		mBtnUninstall = (Button) findViewById(R.id.btn_detail_action_extra);
		mBtnInstall.setOnClickListener(this);
		mBtnUninstall.setOnClickListener(this);
		mPbProgress = (ProgressBar) findViewById(R.id.pb_detail_download);

		InitActionBar();
		//		getActionBar().setDisplayHomeAsUpEnabled(true);
		//		getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.main)));
		getActionBar().setTitle("vStore");

		item = ProductDTO.current;
		if(item != null)
		{
			Update();
			updateStt();
			AddRelatedItems(item.id);
			//			if(!isChecking)
			//			{
			//				(new Handler()).postDelayed(r,1000);
			//				isChecking = true;
			//			}
			// Check if item is downloading
			//			CheckDownloading();
		}
		else
		{
			int id = getIntent().getIntExtra(Constant.ITEM_ID_KEY, -1);
			if(id == -1)
				finish();
			else
				(new Loader()).execute(id);
			AddRelatedItems(id);
		}


	}
	Runnable r=new Runnable()
	{
		public void run() 
		{
			ProductDTO.VerifyAppStatus(SceneDetailItemActivity.this, item);
			switch (item.status) {
			case Constant.APP_STT_INSTALLED:
				SceneDetailItemActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						mBtnInstall.setText(R.string.detail_activity_open_app_name);
						mBtnUninstall.setText(R.string.detail_activity_remove_app);
						mBtnInstall.setVisibility(View.VISIBLE);
						mBtnUninstall.setVisibility(View.VISIBLE);

					}
				});
				break;
			case Constant.APP_STT_UPDATE:
				SceneDetailItemActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						mBtnInstall.setText(R.string.detail_activity_open_app_name);
						mBtnInstall.setVisibility(View.VISIBLE);

						mBtnUninstall.setText(R.string.detail_activity_update_app);
						mBtnUninstall.setVisibility(View.VISIBLE);
					}
				});
				break;
			case Constant.APP_STT_DOWNLOADING:
			case Constant.APP_STT_DOWNLOADED:
				int downloadID = DownloadQuere.CheckDownloading(item.id);
				if(downloadID != -1)
				{
					DownloadTask task = DownloadQuere.mTaskQuere.get(downloadID);
					if(! task.IsFinished())
						// if downloading is still in process
					{
						mBtnInstall.setVisibility(View.INVISIBLE);
						mBtnUninstall.setVisibility(View.INVISIBLE);
						item.status = Constant.APP_STT_DOWNLOADING;
						task.ChangeProgressBar(mPbProgress);
					}
			
					else
					{
						DownloadQuere.ClearTask(task);
						mBtnInstall.setText(R.string.detail_activity_downloaded_app);
						item.status = Constant.APP_STT_DOWNLOADED;
						mBtnInstall.setVisibility(View.VISIBLE);
						mBtnUninstall.setVisibility(View.INVISIBLE);
					}
				}
				break;
			case Constant.APP_STT_NOTHING:
				SceneDetailItemActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						mBtnInstall.setText(R.string.detail_activity_view_app);
						mBtnInstall.setVisibility(View.VISIBLE);

						mBtnUninstall.setVisibility(View.INVISIBLE);
					}
				});
				break;
			default:
				SceneDetailItemActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						mBtnInstall.setText(R.string.detail_activity_view_app);
						mBtnInstall.setVisibility(View.VISIBLE);

						mBtnUninstall.setVisibility(View.INVISIBLE);
					}
				});
				break;
			}
			//			CheckDownloading();   			
		}
	};
	private boolean isChecking = false;
	void AddRelatedItems( int ItemId)
	{
		PageHorizalGalleryFragment hlv_1 = PageHorizalGalleryFragment.instance(this, Constant.HORIZALLIST_SAMEPUBLISHER,((Integer)ItemId).toString() ,getString(R.string.related_publisher));
		if(hlv_1 != null)
			getSupportFragmentManager().beginTransaction()
			.add(R.id.ll_detail_related, hlv_1).commit();
		try{
			PageHorizalGalleryFragment hlv_2 = PageHorizalGalleryFragment.instance(this, Constant.HORIZALLIST_SAMECAT , ((Integer)ItemId).toString(),getString(R.string.related_category));
			if(hlv_2 != null)
				getSupportFragmentManager().beginTransaction()
				.add(R.id.ll_detail_related, hlv_2).commit();
		}catch(Exception e){};
	}

	private void CheckDownloading() {

		int downloadID = DownloadQuere.CheckDownloading(item.id);
		if(downloadID != -1)
		{
			DownloadTask task = DownloadQuere.mTaskQuere.get(downloadID);
			if(task.IsFinished() == false)
			{
				// if downloading is still in process
				mBtnInstall.setVisibility(View.INVISIBLE);
				mBtnUninstall.setVisibility(View.INVISIBLE);
				item.status = Constant.APP_STT_DOWNLOADING;
				task.ChangeProgressBar(mPbProgress);
			}
			else
			{
				// if downloading is finished 
				DownloadQuere.ClearTask(task);
				mBtnInstall.setText(R.string.detail_activity_downloaded_app);
				item.status = Constant.APP_STT_DOWNLOADED;
				mBtnInstall.setVisibility(View.VISIBLE);
				mBtnUninstall.setVisibility(View.INVISIBLE);
			}
		}
		else	
		{
			// if package is already downloaded
			if(Installation.AlreadyDownloaded(this, item.packageName) == true)
			{
				item.status = Constant.APP_STT_DOWNLOADED;
				this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						mBtnInstall.setText(R.string.detail_activity_downloaded_app);
						mBtnInstall.setVisibility(View.VISIBLE);
						mBtnUninstall.setVisibility(View.INVISIBLE);
					}
				});

			}
			// check if item was installed
			PackageInfo pi = Installation.StatusApp(getApplicationContext(), item.packageName);
			if(pi != null)
			{
				Log.d("update stt", "abc");
				if(pi.versionCode >= Integer.parseInt(item.version))
				{

					item.status = Constant.APP_STT_INSTALLED;

					this.runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							mBtnInstall.setText(R.string.detail_activity_open_app_name);
							mBtnUninstall.setText(R.string.detail_activity_remove_app);
							mBtnInstall.setVisibility(View.VISIBLE);
							mBtnUninstall.setVisibility(View.VISIBLE);

						}
					});
				}

				else
				{
					this.runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							mBtnInstall.setText(R.string.detail_activity_open_app_name);
							mBtnInstall.setVisibility(View.VISIBLE);

							mBtnUninstall.setText(R.string.detail_activity_update_app);
							mBtnUninstall.setVisibility(View.VISIBLE);
						}
					});
					item.status = Constant.APP_STT_UPDATE;
				}
				mBtnInstall.setVisibility(View.VISIBLE);


				// remove apk after installing
				Installation.DeleteApk(SceneDetailItemActivity.this, item.packageName);

				// post installled success event to server
				String deviceID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
				Installation.PostInfoInstallSuccess(deviceID, item.id + "");
			}

		}
		//		isChecking = false;
	}

	void updateStt()
	{
		if(item != null)
		{
			(new Thread(r)).start();
			//				(new Handler()).postDelayed(r,1000);
			isChecking = true;
		}
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		Log.i("TAG", "Resume!!");
		updateStt();

	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		//unregisterReceiver(myReceiver);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.scene_detail_item, menu);
		if(android.os.Build.VERSION.SDK_INT >= 11)
		{
			count = menu.findItem(R.id.action_notification).getActionView();

			count.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					MainActivity.isCheckedNotification= true;

					SharedPreference sharedpref = new SharedPreference(SceneDetailItemActivity.this);
					DateFormat df = new SimpleDateFormat("dd MM yyyy");
					Date currDate = Calendar.getInstance().getTime();
					sharedpref.setLastestDate(df.format(currDate));

					Intent intent = new Intent(SceneDetailItemActivity.this, SceneNotificationsActivity.class);
					startActivityForResult(intent,11);
				}
			});


			notifCount = (TextView) count.findViewById(R.id.tv_mainview_number_notification);
			notiLay = (FrameLayout) count.findViewById(R.id.fl_mainview_notification);
			//		count.setVisibility(View.INVISIBLE);
			//		
			if(isCheckedNotification)
				notiLay.setVisibility(View.INVISIBLE	);
			notification = menu.findItem(R.id.action_notification);
			notification.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
			SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
					.getActionView();
			searchView.setSearchableInfo(searchManager
					.getSearchableInfo(getComponentName()));
		}
		listNotf = MainActivity.listnotf;
		_messageHandler.sendMessage(Message.obtain(_messageHandler, NOTIFICATION_COMING, 0, 0, listNotf));

		return true;

	}
	public Handler _messageHandler = new Handler(){


		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == NOTIFICATION_COMING)
			{

				if(listNotf == 0 || MainActivity.isCheckedNotification)
					notiLay.setVisibility(View.INVISIBLE);
				//					notification.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
				else
				{
					notiLay.setVisibility(View.VISIBLE);
					//					notification.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
					notifCount.setText(listNotf + "");
				}
			}

		}
	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.finish();
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	public void Update( )
	{
		((TextView)findViewById(R.id.tv_detail_description)).setText(item.description);
		((TextView)findViewById(R.id.tv_detail_title)).setText(item.name);
		((TextView)findViewById(R.id.tv_detail_publisher)).setText(item.publisher);
		((TextView)findViewById(R.id.tv_detail_cat)).setText(item.category.trim());
		((TextView)findViewById(R.id.tv_detail_size)).setText(item.size);

		Typeface tf = Typeface.createFromAsset(getAssets(),"Roboto-Light.ttf");
		((TextView)findViewById(R.id.tv_detail_title)).setTypeface(tf);
		((TextView)findViewById(R.id.tv_detail_description)).setTypeface(tf);

		ImageView thumbnail = (ImageView) findViewById(R.id.iv_detail_icon);
		if(item.imgURL != null && !item.imgURL.contains("http"))
			item.imgURL = Helper.SERVICE_URL + item.imgURL;
		//		ImageLoader.getInstance().displayImage(item.imgURL, thumbnail);
		ImageDTO.displayImage(item.imgURL, thumbnail);

		LinearLayout scr_shots = (LinearLayout) findViewById(R.id.ll_detail_screenshots);
		String url="";
		for(int i = 0 ; i < item.screenShots.size();i++)
		{

			if(item.screenShots.get(i) != null && !item.screenShots.get(i).contains("http"))
				url = Helper.SERVICE_URL + item.screenShots.get(i);
			ImageView iv = new ImageView(this);
			iv.setScaleType(ScaleType.FIT_CENTER);
			ImageLoader.getInstance().displayImage(url, iv);


			LayoutParams lay = new LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
			lay.setMargins(4, 2, 4, 2);


			scr_shots.addView(iv,lay);
		}
	}

	public class Loader extends AsyncTask<Integer, Void, ProductDTO>{
		@Override
		protected ProductDTO doInBackground(Integer... params) {

			ProductDTO prod = DAO.ProductDAO.GetProd(params[0]);
			return prod;
		}      

		@Override
		protected void onPostExecute(ProductDTO prod) {
			item = prod;


			Update();
			updateStt();
			//			if(!isChecking)
			//			{
			//				(new Handler()).postDelayed(r,1000);
			//				isChecking = true;
			//				
			//			}

		}

		@Override
		protected void onPreExecute() {		

		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v== mBtnUninstall)
		{
			if(item.status == Constant.APP_STT_INSTALLED)
			{
				Uri uri = Uri.fromParts("package", item.packageName, null);

				Intent it = new Intent(Intent.ACTION_DELETE, uri);

				startActivity(it);
			}
			else if( item.status == Constant.APP_STT_UPDATE)
				Install();
		}else
			if(v == mBtnInstall)
			{
				if(item.status == Constant.APP_STT_NOTHING )
				{
					mBtnUninstall.setVisibility(View.INVISIBLE);
					mBtnInstall.setVisibility(View.INVISIBLE);
					Install();
				}
				if(item.status == Constant.APP_STT_DOWNLOADED)
				{
					String path = Environment.getExternalStorageDirectory()
							.getAbsoluteFile()
							+ "/Download/" + item.packageName + ".apk";
					if(Installation.Install(this, path) == false)
					{
						Log.i("TAG", "Error when open app" + item.packageName);
					}
					//				// install app
					//				String path = Environment.getExternalStorageDirectory()
					//						.getAbsoluteFile()
					//						+ "/Download/" + item.packageName + ".apk";
					//				if(Installation.Install(this, path) == false)
					//				{
					//					Log.i("TAG", "Error when open app" + item.packageName);
					//				}
				}
				if(item.status == Constant.APP_STT_INSTALLED || item.status == Constant.APP_STT_UPDATE)
				{
					// open app
					if(Installation.OpenApp(this, item.packageName) == false)
					{
						Log.i("TAG", "Error when open app" + item.packageName);
					}
				}
			}
	}

	private void Install() {
		String url = URL_HEADER + item.filePath;
		final String packageName = item.packageName;
		DownloadTask downloader = new DownloadTask(this, mPbProgress, new IOnDownload() {

			@Override
			public void OnFinished() {
				// TODO Auto-generated method stub

				mBtnInstall.setVisibility(View.VISIBLE);
				mBtnInstall.setText(getText(R.string.detail_activity_downloading_app));
				String path = Environment.getExternalStorageDirectory()
						.getAbsoluteFile()
						+ "/Download/" + packageName + ".apk";
				File file = new File(path);

				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.putExtra("productID", SceneDetailItemActivity.this.item.id);
				intent.setDataAndType(Uri.fromFile(file),
						"application/vnd.android.package-archive");
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				getApplicationContext().startActivity(intent);
			}

			@Override
			public void OnError() {
				// TODO Auto-generated method stub
				try{
					SceneDetailItemActivity.this.mBtnInstall.setVisibility(View.VISIBLE);
				}catch(Exception e){};
			}
		});	
		DownloadQuere.Add(this, downloader, item.id, url, item.packageName);
	}
}
